package com.hmall.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final JwtTool jwtTool;

    private final AntPathMatcher antPathMatcher;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        if (isExclude(request.getPath().toString())) {
            //放行不需要身份验证的路由
            //放行
            return chain.filter(exchange);
        }
        List<String> authorizations = request.getHeaders().get(authProperties.getAuthorization());
        //获取头
        String token = null;
        if (authorizations != null && !CollUtil.isEmpty(authorizations)) {
            token = authorizations.get(0);
        }
        Long userId = null;
        try {
            //解析jwt获取用户id放入请求头，向下游传送
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//终止
        }
//传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange newExchange = exchange.mutate().request(builder ->
                builder.header(authProperties.getUserInfo(), userInfo)).build();
//        ServerHttpRequest newRequest = request.mutate()
//                .header(authProperties.getUserInfo(), userId.toString()) // 将 userId 放入请求头
//                .build();
//        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        return chain.filter(newExchange);


    }

    private boolean isExclude(String path) {
//        路径匹配器
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
